let util = require('./util.js')

let charset = require('superagent-charset')
let request = charset(require('superagent'))
let cheerio = require('cheerio')

function _Get(url, callback) {
    request.get(url)
        .set('Accept','*/*')
        .set('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.7.12954.400')
        .set('Accept-Language','zh-CN')
        .charset('gbk')
        .end(callback)
}

function get_history_data(code, type = 'd', count = 320) {
    let url = ''
    if (type == 'd') {
        url = util.URL.history_data_day
    } else if (type == 'w') {
        url = util.URL.history_data_week
    } else if (type == 'm') {
        url = util.URL.history_data_month
    } else if (type == 'm5') {
        url = util.URL.history_data_minite_5
    } else if (type == 'm30') {
        url = util.URL.history_data_minite_30
    } else if (type == 'm60') {
        url = util.URL.history_data_minite_60
    }
    url = url.replace('{$code}',code).replace('{$count}',count)
    return new Promise(function(resolve,reject){
        _Get(url,(err, res) => {
                if(err) {
                    reject(err)
                    return;
                }
                let response = new Function("return " + res.text)();
                let raw = []
                if(response.code == 0) {
                    if(type == 'd')
                        raw = response.data[code].qfqday
                    else if (type == 'w')
                        raw = response.data[code].qfqweek
                    else if (type == 'm')
                        raw = response.data[code].qfqmonth
                    else if (type == 'm5')
                        raw = response.data[code].qfqm5
                    else if (type == 'm30')
                        raw = response.data[code].qfqm30
                    else if (type == 'm60')
                        raw = response.data[code].qfqm60
                    let bars = {
                        date: [],
                        open: [],
                        high: [],
                        low: [],
                        close: [],
                        volume: [],
                        raw: raw
                    }
                    for (let line of raw) {
                        bars.date.push(line[0])
                        bars.open.push(parseFloat(line[1]))
                        bars.high.push(parseFloat(line[2]))
                        bars.close.push(parseFloat(line[3]))
                        bars.low.push(parseFloat(line[4]))
                        bars.volume.push(parseFloat(line[5]))

                    }
                    resolve(bars)
                }else {
                    reject('Error Code:' + res.code)
                }
            })
    })
}

function get_minite_data(code){
    let url = util.URL.history_data_minite.replace(/\{\$code\}/g, code)
    return new Promise(function(resolve, reject) {
        _Get(url,(err, res) => {
            if(err) {
                reject(err)
                return
            }
            let response = new Function('return ' + res.text)()
            if(response.code == 0) {
                let raw = response.data[code].data.data
                let data = {time:[],price:[],volume:[]}
                for(let line of raw) {
                    let tmp = line.split(' ')
                    data.time.push(tmp[0])
                    data.price.push(parseFloat(tmp[1]))
                    data.volume.push(parseInt(tmp[2]))
                }
                resolve(data)
            }else {
                reject('Error Code:' + response.code)
            }
        })
    })
}

function get_stock_list() {
    let url = util.URL.stock_list
    return new Promise(function(resolve,reject) {
        _Get(url, (err, res) => {
            if(err) {
                reject(err)
                return
            }
            let $ = cheerio.load(res.text)
            let data = {name:[] ,code: []}
            $("#quotesearch ul li").each((i, item) => {
                let codes = $(item).text();
                let tmp = /([^\(\)]*)\((\S*)\)/.exec(codes)
                data.name.push(tmp[1])
                data.code.push(tmp[2])
            })
            resolve(data)
        })
    })
}
function get_fund_view(date, type = '', page = 0) {
    let tmp0 = new Date(date),tmp1 = new Date()
    let year = tmp0.getFullYear(),month = tmp0.getMonth(),year1 = tmp1.getFullYear(),month1 = tmp1.getMonth()
    return new Promise((resolve, reject) => {
        if(year > year1 || (year <= year1 && month > month1)) {
            reject('日期错误')
            return;
        }else {
            let m = parseInt((month + 1)/3)*3
            date = year + '-' + (m<10?'0'+ m:m) + '-' + ((m == 3||m == 12)?31:30)
            let url = ''
            if(type == 'inc') {
                url = util.URL.fund_view_inc
            }else if (type == 'desc') {
                url = util.URL.fund_view_desc
            }else if (type == 'new') {
                url = util.URL.fund_view_new
            }else if (type == 'clear') {
                url = util.URL.fund_view_clear
            }else {
                url = util.URL.fund_view
            }
             url = url.replace('{$page}', page).replace('{$date}', date)
            _Get(url, (err, res) => {
                if(err) {
                    reject(err)
                    return
                }else {
                    let response = new Function("return " + res.text)();
                    if(response.code == 0) {
                        resolve(response.data)
                    }else {
                        reject('Error Code:' + response.code)
                    }
                }
            })
        }
    })
}
function get_fund_view_inc(date, page = 1) {
    get_fund_view(date, 'inc', page)
}
function get_fund_view_desc(date, page = 1) {
    get_fund_view(date, 'desc', page)
}
function get_fund_view_new(date, page = 1) {
    get_fund_view(date, 'new', page)
}
function get_fund_view_clear(date, page = 1) {
    get_fund_view(date, 'clear', page)
}
function get_ths_hy() {
    let url = util.URL.ths_hy
    return new Promise((resolve, reject) => {
        _Get(url, (err, res) => {
            if(err) {
                reject(err)
                return
            }
            let $ = cheerio.load(res.text)
            let data = []
            $('.cate_group .cate_items a').each((i, item) => {
                let href =  $(item).attr('href')
                let hy = {}
                hy.name = $(item).text();
                let reg = /\/code\/([0-9]*)\/$/.exec(href)
                hy.code = reg[1]
                data.push(hy)
            })
            resolve(data)
        })
    })
}

function get_hy_stock(code, page = 1){
    let url = util.URL.ths_hy_stock.replace('{$code}', code).replace('{$page}', page)
    return new Promise((resolve, reject) => {
        request(url)
            .set('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8')
            .set('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.7.12954.400')
            .set('Accept-Language','zh-CN')
            .set('Cookie', 'Hm_lvt_78c58f01938e4d85eaf619eae71b4ed1=1525826090; historystock=002930; spversion=20130314; v=AvXykOZ-w0YnZyf6IShrdWy_BHqicqnUcyaN2HcasWy7ThvnP8K5VAN2ldsE')
            .charset('gbk')
            .set('Host', 'q.10jqka.com.cn')

            .end((err, res) => {
            if(err) {
                reject(err)
                return
            }
            let $ = cheerio.load(res.text)
            let data = {data:[],pages:0,current:0}
            $('table.m-table tbody tr').each((i, item) => {
                let tds = $(item).children("td")
                let tm = {}
                tm.code = $(tds[1]).text()
                tm.name = $(tds[2]).text()
                data.data.push(tm)
            })
            let page = $('#m-page').find('.page_info')
            if(page != undefined) {
                let tm = page.text()
                let p = tm.split('/')
                data.pages = parseInt(p[1])
                data.current = parseInt(p[0])
            }
            resolve(data)
        })
    })
}
function get_history_hy(code, type = 'd') {
    let url = ''
    if(type == 'd') {
        url = util.URL.ths_hy_history_day.replace('{$code}', code)
    }else if(type == 'w') {
        url = util.URL.ths_hy_history_week.replace('{$code}', code)
    }else if(type == 'm') {
        url = util.URL.ths_hy_history_month.replace('{$code}', code)
    }else {
        url = util.URL.ths_hy_history_day.replace('{$code}', code)
    }
    return new Promise((resolve, reject) => {
        request(url)
            .set('Accept','*/*')
            .set('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.7.12954.400')
            .set('Accept-Language','zh-CN')
            .set('Cookie', 'spversion=20130314; log=; Hm_lvt_78c58f01938e4d85eaf619eae71b4ed1=1525792569,1525879779,1525965181; Hm_lpvt_78c58f01938e4d85eaf619eae71b4ed1=1525965181; __utma=156575163.1487556645.1525879791.1525879791.1525965211.2; __utmb=156575163.1.10.1525965211; __utmc=156575163; __utmz=156575163.1525965211.2.2.utmcsr=10jqka.com.cn|utmccn=(referral)|utmcmd=referral|utmcct=/; v=Ali1ISF5ts-qWppLJuPnFDIpKY3nQb3kHqSQT5JJpJVEN_KxOlGMW261YNjh')
            .charset('gbk')
            .set('Host', 'q.10jqka.com.cn')
            .set('Referer','http://q.10jqka.com.cn/thshy/detail/code/' + code + '/')
            .buffer(true)
            .end((err, res) => {
                if(err) {
                    reject(err)
                    return
                }
                let reg = /\w*\(([^\)]*)\)/.exec(res.text)
                let response = new Function('return' + reg[1])()
                let data = {name: response.name,date:[],open:[],high:[],low:[],close:[],volume:[],money:[]}
                let datas = response.data.split(';')
                datas.forEach((item) => {
                    let tmp = item.split(',')
                    data.date.push(tmp[0])
                    data.open.push(parseFloat(tmp[1]))
                    data.high.push(parseFloat(tmp[2]))
                    data.low.push(parseFloat(tmp[3]))
                    data.close.push(parseFloat(tmp[4]))
                    data.volume.push(parseFloat(tmp[5]))
                    data.money.push(parseFloat(tmp[6]))
                })
                resolve(data)
            })
    })
}
function get_hy_minite(code) {
    let url = util.URL.ths_hy_minite.replace('{$code}', code)
    return new Promise((resolve, reject) => {
        request.get(url).set('Accept','*/*')
            .set('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.7.12954.400')
            .set('Accept-Language','zh-CN')
            .set('Cookie', 'spversion=20130314; log=; Hm_lvt_78c58f01938e4d85eaf619eae71b4ed1=1525792569,1525879779,1525965181; Hm_lpvt_78c58f01938e4d85eaf619eae71b4ed1=1525965181; __utma=156575163.1487556645.1525879791.1525879791.1525965211.2; __utmb=156575163.1.10.1525965211; __utmc=156575163; __utmz=156575163.1525965211.2.2.utmcsr=10jqka.com.cn|utmccn=(referral)|utmcmd=referral|utmcct=/; v=Ali1ISF5ts-qWppLJuPnFDIpKY3nQb3kHqSQT5JJpJVEN_KxOlGMW261YNjh')
            .charset('gbk')
            .set('Host', 'q.10jqka.com.cn')
            .set('Referer','http://q.10jqka.com.cn/thshy/detail/code/' + code + '/')
            .buffer(true)
            .end((err, res) => {
                if(err) {
                    reject(err)
                    return
                }
                let reg = /\w*\(([^\)]*)\)/.exec(res.text)
                let response = new Function('return' + reg[1])()

                if(response['bk_' + code]) {
                    let bk = response['bk_' + code]
                    let data = {name:bk.name,date:[],price:[],volume:[]}
                    let datas = bk.data.split(';')
                    datas.forEach((item) => {
                        let tmp = item.split(',')
                        data.date.push(tmp[0])
                        data.price.push(parseFloat(tmp[1]))
                        data.volume.push(parseFloat(tmp[4]))
                    })
                    resolve(data)
                }else {
                    reject('未获得' + code + '数据，请检查板块代码是否正确！')
                }
            })
    })
}
function get_finance(code, variety = 'MGSY_JB') {

    return new Promise((resolve, reject) => {
        if(util._FINANCE_MAP_[variety]  == undefined) {
            reject('财务类目错误')
            return
        }
        let type = '01'
        if(/^6[0-9]{5}$/.test(code)) {
            type = '01'
        }else if(/^[0,3][0-9]{5}$/.test(code)) {
            type = '02'
        }else {
            reject('Stock Code Error')
            return
        }
        let url = util.URL.finance_abstract.replace('{$code}', code).replace('{$type}', type)
        request.get(url)
            .set('Accept','*/*')
            .set('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.7.12954.400')
            .set('Accept-Language','zh-CN')
            .end((err, res) => {
                if(err) {
                    reject(err)
                    return
                }
                let $ = cheerio.load(res.text)
                let data = {name:'',date:[],value:[]}
                let trs = $('#tablefont tbody tr')
                let date_tr = trs[0]
                let value_tr = trs[util._FINANCE_MAP_[variety]]
                let value_tds = $(value_tr).children('td')
                let date_tds = $(date_tr).children('td')
                console.log(trs[0])
                for(let i = 0;i < date_tds.length; i++){
                    let item = date_tds[i]
                    if(i == 0) {
                        data.name = $(value_tds[i]).text()
                        continue
                    }
                    data.date.push($(item).text().replace(/[\s\n]*/g,''))
                    data.value.push($(value_tds[i]).text().replace(/[\s\n]*/g,''))
                };
                resolve(data)
        })
    })
}
function get_money_flow(code) {
    return new Promise((resolve, reject) => {
        let type = '1'
        if(/^6[0-9]{5}$/.test(code)) {
            type = '1'
        }else if(/^[0,3][0-9]{5}$/.test(code)) {
            type = '2'
        }else {
            reject('Stock Code Error')
            return
        }
        let url = util.URL.money_flow.replace('{$code}', code).replace('{$type}', type)
        request.get(url)
            .set('Accept','*/*')
            .set('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.7.12954.400')
            .set('Accept-Language','zh-CN')
            .charset('gbk')
            .buffer(true)
            .end((err, res) => {
                if(err) {
                    reject(err)
                    return
                }
                let response = new Function('return ' + res.text)();
                let data = {date:[],close:[],chg:[],inflow:[],inflow_rate:[],
                    super_inflow:[],super_inflow_rate:[],
                    b_inflow:[],b_inflow_rate:[],
                    m_inflow:[],m_inflow_rate:[],
                    s_inflow:[],s_inflow_rate:[]}
                let datas = response
                for(let i = 0;i < datas.length;i++) {
                    let items = datas[i].split(',')
                    data.date.push(items[0])
                    data.inflow.push(parseFloat(items[1]))
                    data.inflow_rate.push(items[2])
                    data.super_inflow.push(items[3])
                    data.super_inflow_rate.push(items[4])
                    data.b_inflow.push(items[5])
                    data.b_inflow_rate.push(items[6])
                    data.m_inflow.push(items[7])
                    data.m_inflow_rate.push(items[8])
                    data.s_inflow.push(items[9])
                    data.s_inflow_rate.push(items[10])
                    data.close.push(items[11])
                    data.chg.push(items[12])
                }
                resolve(data)
            })
    })
}
function get_executives(code, page = 1) {
    let url = util.URL.ggcg.replace('{$code}', code).replace('{$page}', page)
    return new Promise((resolve, reject) => {
        request.get(url)
            .set('Accept','*/*')
            .set('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.7.12954.400')
            .set('Accept-Language','zh-CN')
            .charset('gbk')
            .buffer(true)
            .end((err, res) => {
                if(err) {
                    reject(err)
                    return
                }
                let response = new Function('return ' + res.text)()
                let data = {pages: response.pages, values:[]}
                for(let i = 0;i < response.data.length; i++) {
                    let tmp = response.data[i].split(",")
                    let item = {}
                    item.GDMC = tmp[4]
                    item.ZJ = tmp[5]
                    item.BDSL = tmp[6]
                    item.BDZLTGBL = tmp[7]
                    item.CGZS = tmp[9]
                    item.ZZGBBL = tmp[10]
                    item.CLTGS = tmp[11]
                    item.BDHZLTGBL = tmp[12]
                    item.BDKSR = tmp[13]
                    item.BDJZR = tmp[14]
                    item.GGR = tmp[15]
                    item.BDZZGBBL = tmp[16]
                    data.values.push(item)
                }
                resolve(data)
            })
    })
}
module.exports.get_history_data = get_history_data
module.exports.get_minite_data = get_minite_data
module.exports.get_stock_list = get_stock_list
module.exports.get_fund_view = get_fund_view
module.exports.get_fund_view_inc = get_fund_view_inc
module.exports.get_fund_view_desc = get_fund_view_desc
module.exports.get_fund_view_new = get_fund_view_new
module.exports.get_fund_view_clear = get_fund_view_clear
module.exports.get_ths_hy = get_ths_hy
module.exports.get_hy_stock = get_hy_stock
module.exports.get_history_hy = get_history_hy
module.exports.get_hy_minite = get_hy_minite
module.exports.get_finance = get_finance
module.exports.get_money_flow = get_money_flow
module.exports.get_executives = get_executives